from django.shortcuts import render, reverse, redirect
from django.http import HttpResponse
from django.views.generic import View
from .forms import User, Sign
from .models import User as Muser
from django.contrib import messages


def index(request):
    return render(request, "index.html")


class IndexView(View):
    def get(self, request):
        return render(request, "signin.html")

    def post(self, request):
        form = Sign(request.POST)
        if form.is_valid():
            user = Muser.objects.filter(username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password')).first()
            if user:
                request.session['user_id'] = user.id
                return redirect(reverse("index"))
            else:
                print("用户名密码错误")
                # messages.add_message(request, messages.INFO, '用户名密码错误')
                messages.info(request, "用户名密码错误")
                return redirect(reverse("signin"))
        else:
            print(form.errors.get_json_data())
            return redirect(reverse("signin"))


class Signup(View):
    def get(self, request):
        return render(request, "signup.html")

    def post(self, request):
        form = User(request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse("signin"))
        else:
            print(form.errors.get_json_data())
            return redirect(reverse('signup'))


def blog(request):
    return render(request, "blog.html")


def video(request):
    return render(request, "video.html")